package cn.tworice.system.service.notice;


import cn.tworice.common.util.StringUtils;
import cn.tworice.mybatis.query.MPJLambdaWrapperX;
import cn.tworice.mybatis.vo.PageParam;
import cn.tworice.system.dao.notice.NoticeDao;
import cn.tworice.system.dao.notice.po.NoticeDO;
import cn.tworice.system.dao.notice.po.dto.NoticeDto;
import cn.tworice.system.dao.user.po.UserDO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class NoticeServiceImpl extends ServiceImpl<NoticeDao, NoticeDO> implements NoticeService {

    @Resource
    private NoticeDao dao;

    @Override
    public Map<String, Object> getPage(PageParam pageParam, NoticeDO entity) {
        return dao.selectJoinPage(pageParam,NoticeDto.class,
                new MPJLambdaWrapperX<NoticeDO>()
                    .selectAll(NoticeDO.class)
                    .selectAs(UserDO::getNickName, NoticeDto::getNickName)
                    .eqIfPresent(NoticeDO::getId, entity.getId())
                    .eqIfPresent(NoticeDO::getTop, entity.getTop())
                    .likeIfPresent(NoticeDO::getTitle, entity.getTitle())
                    .leftJoin(UserDO.class, UserDO::getId, NoticeDO::getCreator)
        );
    }

    @Override
    public String updateOrInsert(NoticeDO entity) {
        String id;
        if(StringUtils.isBlank(entity.getId())){
            entity.setId(id = StringUtils.generateUuid());
            dao.insert(entity);
        }else{
            updateById(entity);
            id = entity.getId();
        }
        return id;
    }

    @Override
    public NoticeDto getInfo(String id) {
        return dao.selectJoinOne(NoticeDto.class, new MPJLambdaWrapperX<NoticeDO>()
                .selectAll(NoticeDto.class)
                .select(UserDO::getNickName)
                .leftJoin(UserDO.class, UserDO::getId, NoticeDto::getCreator)
                .eq(NoticeDto::getId, id)
        );
    }

    @Override
    public boolean remove(String[] ids) {
        return dao.deleteBatchIds(Arrays.asList(ids)) > 0;
    }

    @Override
    public boolean saveBatch(List<NoticeDO> list) {
        list.forEach(item->{
            item.setId(StringUtils.generateUuid());
        });
        return dao.insertBatch(list,list.size());
    }
}
